package kd.lxj.report;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import kd.bos.algo.DataSet;
import kd.bos.algo.JoinType;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.db.DBRoute;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.FilterItemInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import net.bytebuddy.implementation.bind.annotation.Super;

public class MaterialPriceListDataPlugin extends AbstractReportListDataPlugin {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private String algoKey = super.getClass().getName();
    private DBRoute dbRoute = DBRoute.of(EntityMetadataCache.getDataEntityType("im_purinbill").getDBRouteKey());

    @Override
    public DataSet query(ReportQueryParam param, Object obj) throws Throwable {
        // 获取查询条件参数值
        List<FilterItemInfo> filters = param.getFilter().getFilterItems();
//			FilterInfo filterInfo = param.getFilter();
        //物料名称
        String material = null;
        //库存组织
        String kc_org = null;
        //查询期间
        String period = null;
        for (FilterItemInfo filterItem : filters) {
            switch (filterItem.getPropName()) {
                case "material":
                    material = (filterItem.getValue() == null) ? null : String.valueOf(((DynamicObject) filterItem.getValue()).getPkValue());
                    break;
                case "kc_org":
                    kc_org = (filterItem.getValue() == null) ? null : String.valueOf(((DynamicObject) filterItem.getValue()).getPkValue());
                    break;
                // 期间
                case "period":
                    period = (filterItem.getValue() == null) ? null : String.valueOf(((DynamicObject) filterItem.getValue()).getPkValue());
                    break;
                default:
                    break;
            }
        }
        if (kc_org == null) {
            throw new KDBizException("请先选择库存组织！");
        }
        if (period == null) {
            throw new KDBizException("请先选择期间！");
        }
        String str = "number,begindate,enddate";
        QFilter filter = new QFilter("id", "=", period);
        DynamicObject periodInfo = BusinessDataServiceHelper.loadSingle("bd_period", str, filter.toArray());
        //期间开始日期
        Date begindate = periodInfo.getDate("begindate");
        //期间结束日期
        Date enddate = periodInfo.getDate("enddate");
        String begindateStr = sdf.format(begindate);
        String enddateStr = sdf.format(enddate);

        //查询取数处理
        List<QFilter> searchFilterList = new ArrayList<>();
        ArrayList selField = new ArrayList();
        selField.add("billentry.material as materialId");
        selField.add("billentry.material.number as material_name");
        selField.add("billentry.actualprice as price");
        selField.add("billentry.amount as amount");
        selField.add("billentry.qty as qty");
        selField.add("billentry.unit.name as unit");

        if (material != null) {
            searchFilterList.add(new QFilter("billentry.material", "=", material));
        }
        searchFilterList.add(new QFilter("org", "=", kc_org));
        searchFilterList.add(new QFilter("biztime", ">=", begindateStr));
        searchFilterList.add(new QFilter("biztime", "<=", enddateStr));
        searchFilterList.add(new QFilter("billstatus", "=", "C"));

        String selfields = String.join(",", selField);
        DataSet dataSet1 = QueryServiceHelper.queryDataSet(algoKey, "im_purinbill", selfields,
                (QFilter[]) searchFilterList.toArray(new QFilter[searchFilterList.size()]), null);
        //价格最高
        DataSet maxSet = dataSet1.select("materialId", "material_name", "price", "amount", "qty", "unit")
                .groupBy(new String[]{"materialId", "material_name", "unit"}).max("price").finish();
        //价格最低
        DataSet minSet = dataSet1.select("materialId", "material_name", "price", "amount", "qty", "unit")
                .groupBy(new String[]{"materialId", "material_name", "unit"}).min("price").finish();
        //最高最低价差=最高-最低
        maxSet = maxSet.select("materialId", "material_name", "unit", "price as max_price");
        minSet = minSet.select("materialId", "material_name", "unit", "price as min_price");
        DataSet diffDataset = maxSet.join(minSet, JoinType.LEFT).on("materialId", "materialId")
                .select("materialId", "material_name", "max_price", "min_price", "max_price-min_price as price_growth", "unit").finish();
        //本月平均价格  = 物料当月采购总金额/总数量
        DataSet sumAmount = dataSet1.select("materialId", "material_name", "amount")
                .groupBy(new String[]{"materialId", "material_name"}).sum("amount").finish();
        DataSet sumQty = dataSet1.select("materialId", "material_name", "qty")
                .groupBy(new String[]{"materialId", "material_name"}).sum("qty").finish();
        //整理数据
        sumAmount = sumAmount.select("materialId", "material_name", "amount as sumAmount");
        sumQty = sumQty.select("materialId", "material_name", "qty as sumQty");
        DataSet avgPrice = sumAmount.join(sumQty, JoinType.LEFT).on("materialId", "materialId")
                .select("materialId", "material_name", "sumAmount", "sumQty", "sumAmount/sumQty as avg_price").finish();
        DataSet resultSet = diffDataset.join(avgPrice, JoinType.LEFT).on("materialId", "materialId").select("material_name", "max_price", "min_price", "price_growth", "avg_price", "unit").finish();

        return resultSet;
    }


}
